package com.loong.testretrofitrxjavamvp.api;

import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author zgq
 * @version 1.0
 * @describe -- 初始化Retrofit并创建API，使用单例模式获取
 * @date 2018/11/13
 */
public class Api {

    private static final int CONNECT_TIMEOUT = 10;
    private static final int READ_TIMEOUT = 20;
    private static final int WRITE_TIMEOUT = 20;

    public static Api instance;
    private final OkHttpClient okHttpClient;
    private ApiService service;

    public static Api getInstance(){
        if (instance == null){
            synchronized (Api.class){
                if (instance == null){
                    instance = new Api();
                }
            }
        }
        return instance;
    }

    public ApiService getService() {
        return service;
    }

    public Api(){
        okHttpClient = getOkHttpClient();
        Gson gson = new GsonBuilder()
                //配置你的Gson
                .setDateFormat("yyyy-MM-dd hh:mm:ss")
                .registerTypeHierarchyAdapter(String.class,STRING)//设置解析的时候null转成""
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                //添加rxjava2适配器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)//配置okHttp
                .build();
        service = retrofit.create(ApiService.class);
    }

    /** 设置okHttp */
    @NonNull
    private OkHttpClient getOkHttpClient() {
        //配置okHttp
        // Debug时才设置Log拦截器，才可以看到
        //OKHttp进行超时设置
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS); // 连接超时时间阈值
        builder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);   // 数据获取时间阈值
        builder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);  // 写数据超时时间阈值
        builder.retryOnConnectionFailure(true);              //错误重连
        builder.addInterceptor(new TokenInterceptor());
        // 创建okhttpClient 将builder建立
        return builder.build();
    }

    /**
     * 自定义TypeAdapter ,null对象将被解析成空字符串
     */
    public static final TypeAdapter<String> STRING = new TypeAdapter<String>() {
        public String read(JsonReader reader) {
            try {
                if (reader.peek() == JsonToken.NULL) {
                    reader.nextNull();
                    return ""; // 原先是返回null，这里改为返回空字符串
                }
                return reader.nextString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
        public void write(JsonWriter writer, String value) {
            try {
                if (value == null) {
                    writer.nullValue();
                    return;
                }
                writer.value(value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}
